package org.useCode.font;

import com.aspose.pdf.*;
import com.aspose.pdf.fonts.FontRepository;
import com.aspose.pdf.fonts.FontSettings;
import com.aspose.pdf.fonts.ResourceManagementOptions;
import com.aspose.pdf.fonts.ResourceManagementOptions.ResourceType;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.Paths;

public class AsposePDFGenerator {

    private static final String RESOURCE_PATH = "fonts/uming.ttf";
    private static final Path TEMP_FONT_PATH = Paths.get("uming.ttf"); // 临时字体文件路径

    public void generatePDF() {
        // 从类路径加载字体文件
        InputStream fontStream = getClass().getClassLoader().getResourceAsStream(RESOURCE_PATH);
        if (fontStream == null) {
            System.err.println("Could not find font file in resources: " + RESOURCE_PATH);
            return;
        }

        // 创建临时字体文件
        try (InputStream in = fontStream;
             OutputStream out = Files.newOutputStream(TEMP_FONT_PATH)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            out.flush();
            System.out.println("Font file extracted to: " + TEMP_FONT_PATH);
        } catch (IOException e) {
            System.err.println("Failed to extract font file to: " + TEMP_FONT_PATH);
            e.printStackTrace();
            return;
        }

        // 创建 PDF 文档
        Document doc = new Document();

        // 设置字体
        FontSettings settings = FontSettings.getDefaultFontInstance();
        settings.setFontFolder(TEMP_FONT_PATH.toString(), true);

        // 添加页面
        Page page = new Page(PaperSize.A4);
        doc.getPages().add(page);

        // 创建段落
        Paragraph paragraph = new Paragraph("你好，世界！");
        paragraph.getFontSettings().setEmbeddingMode(FontEmbeddingMode.EMBEDDED);

        // 将段落添加到页面
        page.getCanvas().drawParagraph(paragraph);

        // 输出 PDF 文件流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        doc.save(baos, SaveFormat.PDF);
        byte[] pdfBytes = baos.toByteArray();

        // 输出 PDF 文件流到客户端或其他地方
        // 例如，发送到 HttpServletResponse 对象
        // response.getOutputStream().write(pdfBytes);

        // 关闭流
        baos.close();

        // 清理临时文件
        Files.deleteIfExists(TEMP_FONT_PATH);

        System.out.println("PDF generated successfully.");
    }

    public static void main(String[] args) {
        AsposePDFGenerator generator = new AsposePDFGenerator();
        generator.generatePDF();
    }
}